package com.zik.rader_and_video.client;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.stereotype.Component;

/**
 * @author zik
 * @Time 2023/6/14 15:12
 * @description 订阅类
 **/
@Slf4j
@Component
public class MqttSubClient {

    public void subScribeDataPublishTopic(String defaultTopic) {
        //订阅test_queue主题
        String[] mqttTopic = defaultTopic.split(",");
        for (String s : mqttTopic) {
            //订阅主题
            subscribe(s, 0);
        }
    }

    /**
     * 订阅某个主题，qos默认为0
     *
     * @param topic 主题
     */
    public void subscribe(String topic) {
        subscribe(topic, 0);
    }

    /**
     * 订阅某个主题
     *
     * @param topic 主题名
     * @param qos qos模式
     */
    public void subscribe(String topic, int qos) {
        try {
            MqttClient client = MqttPushClient.getClient();
            if (client == null) {
                return;
            }
            client.subscribe(topic, qos);
            log.info("订阅主题:{}", topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}


